import router from '@/router'
import { accountLogin, getRoleMenus, getUserById } from '@/service/login/login'
import { localCache } from '@/utils/cache'
import { mapMenusToPermissions, mapMenusToRoutes } from '@/utils/map-menus'
import { defineStore } from 'pinia'
import useMainStore from '../main/main'
import type { IAccount } from '@/types'
import { LOGIN_TOKEN } from '@/global/constants'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any[]
  permissions: string[]
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: localCache.getCache(LOGIN_TOKEN) || '',
    userInfo: localCache.getCache('userInfo') || {},
    userMenus: localCache.getCache('userMenus') || [],
    permissions: localCache.getCache('permissions') || []
  }),
  actions: {
    async accountLoginAction(account: IAccount) {
      // 1.获取登录信息
      const loginRes = await accountLogin(account)
      const { id, token } = loginRes.data
      this.token = token

      // 2.保存在cache中
      localCache.setCache(LOGIN_TOKEN, token)

      // 3.获取用户信息
      const userRes = await getUserById(id)
      console.log(userRes)
      this.userInfo = userRes.data
      localCache.setCache('userInfo', this.userInfo)

      // 4.根据role的id获取菜单
      const roleId = this.userInfo.role.id
      const menuRes = await getRoleMenus(roleId)
      let userMenus = menuRes.data
      this.userMenus = menuRes.data
      localCache.setCache('userMenus', this.userMenus)

      // 5.保存权限信息
      const permissions = mapMenusToPermissions(this.userMenus)
      this.permissions = permissions
      localCache.setCache('permissions', this.permissions)

      // 5.获取所有的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
      // 5.动态添加路由
      const routes = mapMenusToRoutes(this.userMenus)
      // console.log(routes)
      routes.forEach((route) => router.addRoute('main', route))

      // 跳转到首页
      router.push('/main')
    },
    loadLocalCacheAction() {
      console.log(12121221)
      // 1.用户进行刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      console.log(userInfo)
      if (token && userInfo && userMenus) {
        console.log(111111)
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 1..请求所有roles/departments数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 2.获取按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 3.动态添加路由
        const routes = mapMenusToRoutes(this.userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore
